#include "stm32f10x.h"
#include "OLED.h"
#define Buffer_Size 10
typedef enum
{
	FAILED=0,
	PASSED=!FAILED
}TextStatus;
uint8_t TxIndex,RxIndex=0;
uint8_t Trans_Buffer[Buffer_Size]={1,2,3,4,5,6,7,8,9,10};
uint8_t Rec_Buffer[Buffer_Size];

void RCC_Configuration(void);
void USART_Config(void);
void SendAndReceive(void);
TextStatus CompareData(void);

int main()
{
	OLED_Init();
	RCC_Configuration();
	USART_Config();
	SendAndReceive();
	TextStatus CompareData();
	OLED_ShowNum(1,1,Rec_Buffer[0],1);
	while(1);
}

void RCC_Configuration()
{
	RCC_HSEConfig(RCC_HSE_ON);
	while (RCC_GetFlagStatus(RCC_FLAG_HSERDY) == RESET);
	RCC_PLLConfig(RCC_PLLSource_HSE_Div1, RCC_PLLMul_9);
	RCC_PLLCmd(ENABLE);
	while(RCC_GetFlagStatus(RCC_FLAG_PLLRDY) == RESET);
	RCC_SYSCLKConfig(RCC_SYSCLKSource_PLLCLK);
	while(RCC_GetSYSCLKSource() != 0x08);
	RCC_PCLK2Config(RCC_HCLK_Div1);
	RCC_APB2PeriphResetCmd(RCC_APB2Periph_GPIOA,ENABLE);
	RCC_APB2PeriphResetCmd(RCC_APB2Periph_USART1,ENABLE);
}
void USART_Config()
{
	GPIO_InitTypeDef GPIO_InitStructure;
	GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF_PP;
	GPIO_InitStructure.GPIO_Pin=GPIO_Pin_9;
	GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
	GPIO_Init(GPIOA, &GPIO_InitStructure);
	
	GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IN_FLOATING;
	GPIO_InitStructure.GPIO_Pin=GPIO_Pin_10;
	GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
	GPIO_Init(GPIOA, &GPIO_InitStructure);
	
	USART_InitTypeDef USART_InitStructure;
	USART_InitStructure.USART_BaudRate=115200;
	USART_InitStructure.USART_HardwareFlowControl=USART_HardwareFlowControl_None;
	USART_InitStructure.USART_Mode=USART_Mode_Tx|USART_Mode_Rx;
	USART_InitStructure.USART_Parity=USART_Parity_No;
	USART_InitStructure.USART_StopBits=USART_StopBits_1;
	USART_InitStructure.USART_WordLength=USART_WordLength_8b;
	USART_Init(USART1,&USART_InitStructure);
	
//	USART_ITConfig(USART1,USART_IT_RXNE,ENABLE);
//	
//	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
//	NVIC_InitTypeDef NVIC_InitStructure;
//	NVIC_InitStructure.NVIC_IRQChannel=USART1_IRQn;
//	NVIC_InitStructure.NVIC_IRQChannelCmd=ENABLE;
//	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=1;
//	NVIC_InitStructure.NVIC_IRQChannelSubPriority=1;
//	NVIC_Init(&NVIC_InitStructure);
	
	USART_Cmd(USART1,ENABLE);
}
void SendAndReceive()
{
	for(uint16_t i=0;i<Buffer_Size;i++)
	{
		while(USART_GetFlagStatus(USART1,USART_FLAG_TC)==RESET);
		USART_SendData(USART1,Trans_Buffer[TxIndex++]);
		while(USART_GetFlagStatus(USART1,USART_FLAG_TXE)==RESET); 
		
		while(USART_GetFlagStatus(USART1,USART_FLAG_RXNE)==RESET);
		Rec_Buffer[RxIndex++]=USART_ReceiveData(USART1);
	}
}
TextStatus CompareData()
{
	for(uint16_t i=0;i<Buffer_Size;i++)
	{
		if(Trans_Buffer[i]!=Rec_Buffer[i])
			return FAILED;
	}
	return PASSED;
}

//void USART1_IRQHandler(void)
//{
//}
